package com.bbs.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.alibaba.fastjson.JSON;
import com.bbs.beans.Subject;

import manager.PersistentManager;

/**
 * 获取所有的主题
 * Servlet implementation class AllSubject
 */
//@WebServlet("/AllSubject")
public class AllSubject extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AllSubject() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		SessionFactory sf = PersistentManager.sharemanager().getSessionFactory();
		Session session = sf.openSession();
			
		Download download = new Download();
		
		Transaction tx = session.beginTransaction();
		
		try{
			Query q = session.createQuery("from Subject");
			download.setSubjects(q.list());
			tx.commit();
			download.setStatus(DownloadInfo.SUCCESS);
			System.out.println(JSON.toJSONString(download));
		}catch(Exception e)
		{
			download.setStatus(DownloadInfo.FAILED);
			tx.rollback();
			e.printStackTrace();
		}finally {
			session.close();
		}
		
		//System.out.println(JSON.toJSONString(download));
		response.getWriter().append(JSON.toJSONString(download));
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	// 上行数据
	public static class Upload
	{
		
	}
	
	
	// 下行数据
	public static class Download
	{
		// 状态
		int status;
		// 所有的主题
		List<Subject> subjects = new ArrayList<Subject>();
		public int getStatus() {
			return status;
		}
		public void setStatus(int status) {
			this.status = status;
		}
		public List<Subject> getSubjects() {
			return subjects;
		}
		public void setSubjects(List<Subject> subjects) {
			this.subjects = subjects;
		}
		
		
	}

}
